package com.bjfu.intelligentrecognizeserver.controller;

import com.bjfu.intelligentrecognizeserver.pojo.entity.*;
import com.bjfu.intelligentrecognizeserver.pojo.vo.KingdomVo;
import com.bjfu.intelligentrecognizeserver.service.SpeciesService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class SpeciesInfoController {
    private final SpeciesService speciesService;
    private final Logger logger = LoggerFactory.getLogger("SpeciesInfoController");
    private static final String UPLOAD_DIR = "C:/Users/17805/Desktop/image/";

    /*@PostMapping("/species/selectSpeciesInfo")
    public ResponseEntity<Integer> addSpeciesInfo(@RequestBody SelectSpeciesInfoDTO selectSpeciesInfoDTO){
        logger.info(selectSpeciesInfoDTO.toString());
        Integer result = speciesService.postSelectSpeciesInfo(selectSpeciesInfoDTO);
        return ResponseEntity.ok(result);
    }*/

    @GetMapping("/species/getAllSpeciesInfo")
    public ResponseEntity<List<SpeciesInfo>> getAllSpeciesInfo() {
        List<SpeciesInfo> species = speciesService.getAllSpecies();
        return ResponseEntity.ok(species);
    }

    @PostMapping("/species/selectSpeciesInfo")
    public ResponseEntity<String> uploadFilesWithText(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("chineseName") String chineseName,
            @RequestParam("latinName") String latinName,
            @RequestParam("sex") String sex,
            @RequestParam("ecosystemType") String ecosystemType,
            @RequestParam("longitude") double longitude,
            @RequestParam("latitude") double latitude,
            @RequestParam("detailAddress") String detailAddress,
            @RequestParam("method") String method,
            @RequestParam("description") String description,
            @RequestParam("userId") Integer userId,
            @RequestParam("province") String province,
            @RequestParam Map<String, String> category
            // 分类字段（如 kingdom、phylum 等）
    ) {
        //先插入字段
        //category包含了界....
        logger.info("category:{}",category);
        //由中文名查到specieId
        Integer specieId = speciesService.getIdByChineseName(chineseName);
        SelectSpeciesInfo selectSpeciesInfo = SelectSpeciesInfo.builder()
                .chineseName(chineseName)
                .latinName(latinName)
                .sex(sex)
                .ecosystemType(ecosystemType)
                .longitude(longitude)
                .latitude(latitude)
                .detailAddress(detailAddress)
                .method(method)
                .description(description)
                .userId(userId)
                .province(province)
                .jie(category.get("jie"))
                .men(category.get("men"))
                .gang(category.get("gang"))
                .mu(category.get("mu"))
                .ke(category.get("ke"))
                .shu(category.get("shu"))
                .speciesId(specieId)
                .build();
        //将信息插入
        Integer infoId = speciesService.addSelectSpeciesInfo(selectSpeciesInfo);
        logger.info("插入后infoId:{}",infoId);
        //再插入图片、视频等路径
        List<String> selectPhotos = new ArrayList<>();
        List<String> selectVideos = new ArrayList<>();
        try {
            logger.info("收到的消息{}", chineseName + " - " + latinName + "，文件数: " + files.length);
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                File dest = new File(UPLOAD_DIR + File.separator + fileName);
                file.transferTo(dest);

                //利用fileName得到上传的数据类型
                String type = fileName.split("\\.")[1];
                //判断数据类型
                if (type.equals("jpg") || type.equals("jpeg") || type.equals("png")) {
                    selectPhotos.add(dest.getAbsolutePath());
                } else {
                    selectVideos.add(dest.getAbsolutePath());
                }
            }
            logger.info("selectPhotos{}",selectPhotos);
            logger.info("selectVideos{}",selectVideos);
            //绑定info_id分别插入
            SelectPhotos selectPhoto = SelectPhotos.builder()
                    .userId(userId)
                    .selectedPhotos(selectPhotos)
                    .selectSpeciesInfoId(infoId)
                    .build();
            SelectAudios selectAudios = SelectAudios.builder()
                    .userId(userId)
                    .selectedAudios(selectVideos)
                    .selectSpeciesInfoId(infoId)
                    .build();
            List<Integer> selectPhotoIds = speciesService.addSelectPhotos(selectPhoto);
            logger.info("selectPhotoIds{}",selectPhotoIds);
            List<Integer> selectAudioIds = speciesService.addSelectAudios(selectAudios);
            logger.info("selectAudioIds{}",selectAudioIds);

            return ResponseEntity.ok("上传成功");
        } catch (IOException e) {
            return ResponseEntity.status(500).body("上传失败");
        }

    }

    @PostMapping("/species/getKingdom")
    public ResponseEntity<List<KingdomVo>> getKingdom() {
        List<Kingdom> kingdoms = speciesService.getKingdom();
        List<KingdomVo> kingdomVos = new ArrayList<>();
        for (Kingdom kingdom : kingdoms) {

            KingdomVo kingdomVo = new KingdomVo();
            kingdomVo.setKingdomName(kingdom.getKingdomName());
            kingdomVo.setKingdomId(kingdom.getKingdomId());
            kingdomVos.add(kingdomVo);
        }
        logger.info(kingdomVos.toString());
        return ResponseEntity.ok(kingdomVos);
    }

    @GetMapping("/species/getCategoryIdByName")
    public ResponseEntity<Integer> getCategoryIdByName(
            @RequestParam("level") String level,
            @RequestParam("name") String name) {
        Integer categoryId = null;
        switch (level) {
            case "men":
                categoryId = speciesService.getMenIdByName(name);
                break;
            case "gang":
                categoryId = speciesService.getGangIdByName(name);
                break;
            case "mu":
                categoryId = speciesService.getMuIdByName(name);
                break;
            case "ke":
                categoryId = speciesService.getKeIdByName(name);
                break;

        }
        logger.info("categoryId: {} , name = {}", categoryId, name);
        return ResponseEntity.ok(categoryId);
    }

    @GetMapping("/species/getCategoryByParentId")
    public ResponseEntity<List<String>> getCategoryByParentId(
            @RequestParam("parentId") Integer parentId,
            @RequestParam("level") String level) {
        //"门"  kindomId = 1
        List<String> categoryS = new ArrayList<>();
        switch (level) {
            case "men":
                categoryS = speciesService.getMenListByKingdomId(parentId);
                break;
            case "gang":
                categoryS = speciesService.getGangListByMenId(parentId);
                break;
            case "mu":
                categoryS = speciesService.getMuListByGangId(parentId);
                break;
            case "ke":
                categoryS = speciesService.getKeListByMuId(parentId);
                break;
        }
        return ResponseEntity.ok(categoryS);
    }
}
